package com.example.demo.controller;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:DELL
 * Date:2025-04-28
 * Time:18:11
 */
@RequestMapping("/session")
@RestController
public class SessionController {
    @RequestMapping("/getC")
    public String getCookie(HttpServletRequest request, HttpServletResponse response){
       /* //获取参数
        String name=request.getParameter("name");*/
        Cookie[] cookies=request.getCookies();
        if(cookies!=null){
            Arrays.stream(cookies).forEach(ck-> System.out.println(ck.getName()+":"+ck.getValue()));
        }
        return "获取Coolie";
    }
    @RequestMapping("/getC2")
    public String getCookie2(@CookieValue("bite")String bite){
       return "从cookie中获取值，bite:"+bite;
    }
    @RequestMapping("/setSess")
    public String setSess(HttpServletRequest request){
        //从cookie中获取到了sessionId,根据sessionId获取session对象,如果没有获取到，会创建一个session对象
        HttpSession session=request.getSession();
        session.setAttribute("name","zhangsan");
        return "设置session成功";
    }
    @RequestMapping("/getSess")
    public String getSess(HttpServletRequest request){
        //从cookie中获取到了sessionId,根据sessionId获取session对象
        HttpSession session=request.getSession();
        String name=(String)session.getAttribute("name");
        return "从session中获取name:"+name;
    }
    /*直接获取session*/
    @RequestMapping("/getSess2")
    public String getSess2(HttpSession session){
        //从cookie中获取到了sessionId,根据sessionId获取session对象
        String name=(String)session.getAttribute("name");
        return "从session中获取name:"+name;
    }
    /*封装获取到的session值*/
    @RequestMapping("/getSess3")
    public String getSess3(@SessionAttribute("name") String name){
        return "从session中获取name:"+name;
    }
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        return "从header中获取信息，userAgent:"+userAgent;
    }
    /*对header进行封装*/
    @RequestMapping("/getHeader1")
    public String getHeader1(@RequestHeader("User-Agent") String userAgent){
        //String userAgent = request.getHeader("User-Agent");
        return "从header中获取信息，userAgent:"+userAgent;
    }
}
